<template>
  <div>
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>运维管理</a-breadcrumb-item>
      <a-breadcrumb-item>工单管理</a-breadcrumb-item>
    </a-breadcrumb>
    <a-card>
      <!-- 查询条件 start-->
      <a-row align="center">
        <a-col :span="16" style="margin-top: 4px">
          <a-form :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left" auto-label-width>
            <a-row :gutter="16" align="center">
              <!--工单名称-->
              <a-col :span="12">
                <a-form-item field="orderTitle" label="工单名称">
                  <a-input v-model="searchModel.orderTitle" placeholder="请输入工单名称" allow-clear />
                </a-form-item>
              </a-col>
              <!--工单状态-->
              <a-col :span="12">
                <a-form-item label="工单状态">
                  <a-select v-model="searchModel.status" placeholder="请选择工单状态" allow-clear>
                    <a-option value="0">进行中</a-option>
                    <a-option value="3">已完成</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <!-- 分割线 -->
        <a-divider style="height: 40px; margin-bottom: 12px" direction="vertical" />
        <a-col :span="2" style="text-align: left; padding-bottom: 12px">
          <a-space :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- 查询条件 end-->
      <!-- 分割线 -->
      <a-divider style="margin-top: 0" />
      <!-- 新建工单按钮 start-->
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon>
                <icon-plus />
              </template>
              新建工单
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- 新建工单按钮 end-->
      <!-- 表格内容  -->
      <a-table :loading="loading" row-key="id" :bordered="{ wrapper: true, cell: true }" :columns="columns" :data="renderData" @page-change="onPageChange" :pagination="pagination" @page-size-change="onPageSizeChange">
        <!-- 计划时间 -->
        <template #planTime="{ record }">
          {{ record.planStartTime + '~' + record.planEndTime }}
        </template>
        <!-- 超时状态 -->
        <template #timeoutStatus="{ record }">
          <a-tag v-if="record.timeoutStatus == 0" color="rgb(var(--green-6))">正常</a-tag>
        </template>
        <!-- 工单状态 -->
        <template #status="{ record }">
          <a-tag v-if="record.status == 3" color="rgb(var(--blue-6))">已完成</a-tag>
          <a-tag v-else color="rgb(var(--red-6))">进行中</a-tag>
        </template>
        <template #operate="{ record }">
          <a-button v-if="!(record.status == 11 || record.status == 10) && record.status > -1" size="small" type="text" status="success" @click="handleStatus(record)">处理</a-button>
          <a-button size="small" type="text" status="success" @click="handleDetail(record)">详情</a-button>
          <a-button size="small" type="text" status="danger" @click="handleDelete(record)">删除</a-button>
        </template>
      </a-table>
      <!-- 新建工单右弹层 start -->
      <a-drawer :width="600" :visible="formDrawer.visible" @cancel="handleFormCancel" @ok="handleSubmitForm" :mask-closable="false">
        <template #title>
          新建工单
        </template>
        <a-form ref="formCreateRef" auto-label-width :model="formDrawer.formModel" label-align="right" v-model:rules="formDrawer.rules">
          <a-row :gutter="24">
            <a-col :span="24">
              <!-- 工单名称 -->
              <a-form-item field="orderTitle" label="工单名称">
                <a-input v-model="formDrawer.formModel.orderTitle" placeholder="请输入工单名称" />
              </a-form-item>
              <!-- 站点名称 -->
              <a-form-item field="stationName" label="站点名称">
                <a-input v-model="formDrawer.formModel.stationName" placeholder="请输入站点名称" />
              </a-form-item>
              <!-- 事件名称 -->
              <a-form-item field="alarmName" label="事件名称">
                <a-input v-model="formDrawer.formModel.alarmName" placeholder="请输入事件名称" />
              </a-form-item>
              <!-- 负责人 -->
              <a-form-item field="chargeBy" label="负责人">
                <a-input v-model="formDrawer.formModel.chargeBy" placeholder="请输入负责人" />
              </a-form-item>
              <!-- 协作人 -->
              <a-form-item field="collaborateFor" label="协作人">
                <a-input v-model="formDrawer.formModel.collaborateFor" placeholder="请输入协作人" />
              </a-form-item>
              <!-- 创建时间 -->
              <a-form-item field="createTime" label="创建时间">
                <a-time-picker v-model="formDrawer.formModel.createTime" show-now-btn format="YYYY-MM-DD HH:mm" show-time @change="onCreateTimeChange" />
              </a-form-item>
              <!-- 计划时间 -->
              <a-form-item field="planTime" label="计划时间">
                <a-range-picker v-model="formDrawer.formModel.planTime" show-now-btn format="YYYY-MM-DD HH:mm" show-time @change="onPlanTimeChange" />
              </a-form-item>
              <!-- 超时状态 -->
              <a-form-item field="timeoutStatus" label="超时状态">
                <a-select v-model="formDrawer.formModel.timeoutStatus" placeholder="请选择超时状态" allow-clear>
                  <a-option label="正常" value="0" />
                  <a-option label="超时" value="1" />
                </a-select>
              </a-form-item>
              <!-- 工单状态 -->
              <a-form-item field="status" label="工单状态">
                <a-select v-model="formDrawer.formModel.status" placeholder="请选择工单状态" allow-clear>
                  <a-option label="进行中" value="0" />
                  <a-option label="已完成" value="3" />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-drawer>
      <!-- 新建工单右弹层 end -->
      <!-- 操作弹框 start -->
      <a-modal width="450px" v-model:visible="operateModalModel.visible" class="modal-box">
        <template #title>
          <icon-close-circle v-if="operateModalModel.type == 1" size="18" style="color: rgb(var(--red-6)); margin-right: 5px" />
          <icon-exclamation-circle v-else size="18" style="color: rgb(var(--orange-6)); margin-right: 5px" />
          确认提示
        </template>
        <div style="text-align: center">是否确认{{ operateModalModel.title }}名称为【{{ operateModalModel.name }}】的数据项？</div>
        <template #footer>
          <div style="text-align: center">
            <a-space>
              <a-button type="primary" status="danger" @click="handleOperateModelCancle">取消</a-button>
              <a-button type="primary" @click="handleOperateModelOk">确认</a-button>
            </a-space>
          </div>
        </template>
      </a-modal>
      <!-- 操作弹框 end -->
      <!-- 工单详情 start -->
      <a-drawer :width="600" :esc-to-close="false" :visible="formDrawer.detailVisible" @ok="handleFormCancel" @cancel="handleFormCancel" :mask-closable="false">
        <template #title>
          工单详情
        </template>
        <a-spin :loading="formDrawer.loading" style="width: 100%; height: auto">
          <a-row :gutter="24">
            <a-col :span="24" style="height: auto; border-right: 1px solid var(--color-border)">
              <a-divider orientation="center">工单信息</a-divider>
              <a-descriptions :align="{ label: 'right' }" :label-style="{ color: 'rgb(var(--color-neutral-10))' }" :column="1" size="large">
                <!-- 工单名称 -->
                <a-descriptions-item label="工单名称：">
                  <a-skeleton v-if="formDrawer.loading" :animation="true">
                    <a-skeleton-line :rows="1" />
                  </a-skeleton>
                  <span v-else>{{ formDrawer.formModel.orderTitle }}</span>
                </a-descriptions-item>
                <!-- 站点名称 -->
                <a-descriptions-item label="站点名称：">
                  <span>{{ formDrawer.formModel.stationName || '-' }}</span>
                </a-descriptions-item>
                <!-- 事件名称 -->
                <a-descriptions-item label="事件名称：">
                  <span>{{ formDrawer.formModel.alarmName || '-' }}</span>
                </a-descriptions-item>
                <!-- 负责人 -->
                <a-descriptions-item label="负责人：">
                  <span>{{ formDrawer.formModel.chargeBy || '-' }}</span>
                </a-descriptions-item>
                <!-- 协作人 -->
                <a-descriptions-item label="协作人：">
                  <span>{{ formDrawer.formModel.collaborateFor || '-' }}</span>
                </a-descriptions-item>
                <!-- 创建时间 -->
                <a-descriptions-item label="创建时间：">
                  <span>{{ formDrawer.formModel.createTime || '-' }}</span>
                </a-descriptions-item>
                <!-- 计划时间 -->
                <a-descriptions-item label="计划时间：">
                  <span>{{ formDrawer.formModel.planStartTime + '-' + formDrawer.formModel.planEndTime }}</span>
                </a-descriptions-item>
                <!-- 完成时间 -->
                <a-descriptions-item label="完成时间：">
                  <span>{{ formDrawer.formModel.completeTime || '-' }}</span>
                </a-descriptions-item>
                <!-- 超时状态 -->
                <a-descriptions-item label="超时状态：">
                  <a-tag v-if="formDrawer.formModel.timeoutStatus == 0" color="rgb(var(--green-6))">正常</a-tag>
                  <a-tag v-else color="rgb(var(--red-6))">超时</a-tag>
                </a-descriptions-item>
                <!-- 工单状态 -->
                <a-descriptions-item label="工单状态：">
                  <a-tag v-if="formDrawer.formModel.status == 3" color="rgb(var(--blue-6))">已完成</a-tag>
                  <a-tag v-else color="rgb(var(--red-6))">进行中</a-tag>
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>
        </a-spin>
      </a-drawer>
      <!-- 工单详情 end -->
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import useLoading from '../../utils/loading'
import { BasePagination } from '../../apis/common'
import { listOrder } from '../../apis/Operationmanage'
import { FormInstance } from '@arco-design/web-vue'
import dayjs from 'dayjs'

const { loading, setLoading } = useLoading(true)

// 生成查询条件对象
const generateSearchModel: any = () => {
  return {
    orderTitle: '',
    status: ''
  }
}

// 查询表单对象
const searchModel = ref(generateSearchModel())

// 设置表格列
const columns = computed<any[]>(() => [
  {
    title: '工单名称',
    dataIndex: 'orderTitle',
    align: 'center',
    width: 100
  },
  {
    title: '站点&设备',
    dataIndex: 'stationName',
    width: 200,
    align: 'center'
  },
  {
    title: '事件名称',
    dataIndex: 'alarmName',
    width: 160,
    align: 'center'
  },
  {
    title: '负责人',
    dataIndex: 'chargeBy',
    align: 'center',
    width: 80
  },
  {
    title: '协作人',
    dataIndex: 'collaborateFor',
    slotName: 'collaborateFor',
    align: 'center',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    slotName: 'createTime',
    width: 180,
    align: 'center'
  },
  {
    title: '计划时间',
    dataIndex: 'planTime',
    slotName: 'planTime',
    width: 360,
    align: 'center'
  },
  {
    title: '完成时间',
    dataIndex: 'completeTime',
    slotName: 'completeTime',
    width: 180,
    align: 'center'
  },
  {
    title: '超时状态',
    dataIndex: 'timeoutStatus',
    slotName: 'timeoutStatus',
    align: 'center',
    width: 120,
    fixed: 'right'
  },
  {
    title: '工单状态',
    dataIndex: 'status',
    slotName: 'status',
    align: 'center',
    width: 100,
    fixed: 'right'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 280,
    slotName: 'operate',
    align: 'center',
    fixed: 'right'
  }
])

// 表格分页参数
const pagination: any = reactive({ ...BasePagination() })

// 表格数据
const renderData = ref<any[]>([])

// 表格页码发生变化
const onPageChange = (val: number) => {
  pagination.current = val
  // 重新加载数据
  fetchData()
}

// 表格每页数量发生变化
const onPageSizeChange = (val: number) => {
  pagination.pageSize = val
  // 重新加载数据
  fetchData()
}

// 查询表格数据
const fetchData = async () => {
  setLoading(true)
  try {
    const params = {
      ...searchModel.value
    }
    const res: any = await listOrder(params)
    if (res.data.code == 200) {
      renderData.value = res.data.rows
      pagination.total = res.data.total
    }
  } catch (err) {
    console.error('工单管理-错误', err)
  } finally {
    setLoading(false)
  }
}

onMounted(async () => {
  await fetchData()
})

// 查询
const search = async () => {
  pagination.current = 1
  await fetchData()
}

// 生成表单模型
const generateFormDrawerModel = () => {
  return {
    visible: false,
    statusVisible: false,
    detailVisible: false,
    loading: false,
    rules: {
      orderTitle: [{ required: true, message: '请输入工单名称' }],
      stationName: [{ required: true, message: '请输入站点名称' }],
      alarmName: [{ required: true, message: '请输入事件名称' }],
      chargeBy: [{ required: true, message: '请输入负责人' }],
      collaborateFor: [{ required: true, message: '请输入协作人' }],
      createTime: [{ required: true, message: '请选择创建时间' }],
      planTime: [{ required: true, message: '请选择计划时间' }],
      timeoutStatus: [{ required: true, message: '请选择超时状态' }],
      status: [{ required: true, message: '请选择工单状态' }]
    },
    formModel: {
      id: 0,
      status: '',
      timeoutStatus: '',
      orderTitle: '',
      stationName: '',
      alarmName: '',
      planTime: undefined,
      chargeBy: '',
      collaborateFor: '',
      createTime: '',
      planStartTime: '',
      planEndTime: '',
      completeTime: undefined
    }
  }
}

// 表单模型
const formDrawer = ref(generateFormDrawerModel())

// 表格实例
const formCreateRef = ref<FormInstance>()

// 创建时间
const onCreateTimeChange = (dateString: any, date: any) => {
  formDrawer.value.formModel.createTime = dayjs(dateString).format('YYYY-MM-DD HH:mm:00')
}

// 计划时间
const onPlanTimeChange = (dateString: any, date: any) => {
  formDrawer.value.formModel.planStartTime = dayjs(dateString[0]).format('YYYY-MM-DD HH:mm:00')
  formDrawer.value.formModel.planEndTime = dayjs(dateString[1]).format('YYYY-MM-DD HH:mm:00')
}

// 新建工单
const handleAdd = () => {
  // 打开表单
  formDrawer.value.visible = true
  // 清空表单数据
  formDrawer.value.formModel = generateFormDrawerModel().formModel
}

// 表单取消
const handleFormCancel = () => {
  formDrawer.value = generateFormDrawerModel()
  formCreateRef.value?.resetFields()
}

// 新建工单-提交表单
const handleSubmitForm = async () => {
  const validate = await formCreateRef.value?.validate()
  if (validate) {
    return
  }
  // 打印右弹层的表单数据
  // 将formDrawer.value.formModel数据添加到renderData中
  renderData.value.push(formDrawer.value.formModel)
  formDrawer.value.visible = false
}

// 操作弹框
const generateOperateModalModel = () => {
  return {
    type: 0,
    visible: false,
    title: '',
    id: 0,
    value: 0,
    name: ''
  }
}

// 操作弹框模型
const operateModalModel = ref(generateOperateModalModel())

// 提示弹框取消
const handleOperateModelCancle = () => {
  operateModalModel.value = generateOperateModalModel()
}

// 处理
const handleStatus = (record: any) => {
  operateModalModel.value.visible = true
  operateModalModel.value.id = record.id
  operateModalModel.value.title = '处理'
  operateModalModel.value.name = record.orderTitle
  operateModalModel.value.type = 2
}

// 提示弹框确认
const handleOperateModelOk = () => {
  // 处理
  if (operateModalModel.value.type == 2) {
    // 将renderData中id为operateModalModel.value.id的数据的status改为1
    renderData.value.forEach((item: any) => {
      if (item.id == operateModalModel.value.id) {
        item.status = 3
      }
    })
    // 获取当前时间并将时间格式化为YYYY-MM-DD HH:mm:ss，并赋值给表格中id为operateModalModel.value.id的数据的completeTime为当前时间
    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
    renderData.value.forEach((item: any) => {
      if (item.id == operateModalModel.value.id) {
        item.completeTime = now
      }
    })
  }
  // 删除
  if (operateModalModel.value.type == 1) {
    console.log(operateModalModel.value.id)
    // 将renderData中id为operateModalModel.value.id的数据删除
    renderData.value = renderData.value.filter((item: any) => item.id != operateModalModel.value.id)
  }
  operateModalModel.value.visible = false
}

// 详情
const handleDetail = async (val: any) => {
  formDrawer.value.detailVisible = true
  formDrawer.value.formModel = val
  // 关闭右弹层后不影响之前的数据
  formDrawer.value = { ...formDrawer.value }
  formDrawer.value.formModel = { ...formDrawer.value.formModel }
}

// 删除数据
const handleDelete = (record: any) => {
  operateModalModel.value.visible = true
  operateModalModel.value.id = record.id
  operateModalModel.value.title = '删除'
  operateModalModel.value.name = record.orderTitle
  operateModalModel.value.type = 1
}
</script>